package com.guojing.jl.webclient.learning;


import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

/**
 * 一旦webclient被创建, 它就是不可变的, 不过可以通过创建另外一个实例来重新指定属性:
 */
@Slf4j
public class C_WebClientFilterDemo {


    @Test
    public void testParam1() {

        WebClient webClient = WebClient.builder().baseUrl("your_url")
                .filter(logRequest())
                .filter((request, next) -> {
                    System.out.println(request.attributes());
                    return next.exchange(request);
                })
                .filter(logResponse())
                .build();

    }

    private ExchangeFilterFunction logRequest() {
        return (clientRequest, next) -> {
            log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
            clientRequest.headers()
                    .forEach((name, values) -> values.forEach(value -> log.info("{}={}", name, value)));
            return next.exchange(clientRequest);
        };
    }

    private ExchangeFilterFunction logResponse() {
        return ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
            log.info("Response: {}", clientResponse.headers().asHttpHeaders().get("property-header"));
            return Mono.just(clientResponse);
        });
    }


}
